package com.estun.backroundManagementService.modules.alarm.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.estun.backroundManagementService.modules.alarm.mapper.AlarmMapper;
import com.estun.backroundManagementService.modules.alarm.mapper.StationAlarmMappingMapper;
import com.estun.backroundManagementService.modules.alarm.model.AlarmResult;
import com.estun.backroundManagementService.modules.alarm.model.StationAlarm;
import com.estun.backroundManagementService.modules.alarm.model.StationAlarmMapping;
import com.estun.backroundManagementService.modules.alarm.service.StationAlarmService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
@AllArgsConstructor
public class StationAlarmServiceImpl extends ServiceImpl<AlarmMapper, StationAlarm> implements StationAlarmService {

    private final AlarmMapper stationAlarmMapper;

    private final StationAlarmMappingMapper stationAlarmMappingMapper;

    @Override
    public StationAlarmMapping getStationCodeByAlarmIndex(String alarmIndex) {
        List<StationAlarmMapping> stationAlarmMappings = stationAlarmMappingMapper.selectList(new QueryWrapper<StationAlarmMapping>()
                .eq("alarm_index", alarmIndex));
        //todo 只提取第一个
        return stationAlarmMappings.get(0);
    }

    @Override
    public List<AlarmResult> getByLatestAlarmList(String opCode) {
        List<StationAlarmMapping> stationAlarmMappings = stationAlarmMappingMapper.selectList(new QueryWrapper<StationAlarmMapping>()
                .eq("op_code", opCode));

        if (stationAlarmMappings.isEmpty()) {
            return Collections.emptyList();
        }

        StationAlarmMapping alarmMapping = stationAlarmMappings.get(0);

        List<StationAlarm> stationAlarms = stationAlarmMapper.selectList(new QueryWrapper<StationAlarm>()
                .eq("station_id", alarmMapping.getStationId()).eq("status", 1));

        List<AlarmResult> filteredAndSortedAlarms = stationAlarms.stream()
                .filter(alarm -> stationAlarmMappings.stream()
                        .anyMatch(mapping -> mapping.getAlarmIndex().equals(alarm.getAlarmIndex())))
                // 根据 updateTime 降序排序
//                .sorted((alarm1, alarm2) -> alarm2.getUpdateTime().compareTo(alarm1.getUpdateTime()))
                .sorted(Comparator.comparing(StationAlarm::getUpdateTime, Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
                // 限制结果只包含最新的五条记录
                .limit(5)
                .map(alarm -> {
                    StationAlarmMapping matchingMapping = stationAlarmMappings.stream()
                            .filter(mapping -> mapping.getAlarmIndex().equals(alarm.getAlarmIndex()))
                            .findFirst()
                            .orElse(null); // 如果没有匹配的项，则返回 null
                    AlarmResult alarmResult = new AlarmResult();
                    alarmResult.setAlarmTime(alarm.getUpdateTime());
                    alarmResult.setContent(matchingMapping != null ? matchingMapping.getContent() : "");
                    alarmResult.setOpCode(opCode);
                    alarmResult.setStationId(alarmMapping.getStationId());
                    alarmResult.setAlarmIndex(matchingMapping.getAlarmIndex());
                    return alarmResult;

                })
                // 收集结果到 List
                .collect(Collectors.toList());

        if (filteredAndSortedAlarms.isEmpty()) {
            return Collections.emptyList();
        }
        return filteredAndSortedAlarms;
    }

    @Override
    public List<StationAlarm> getAlarmListByStationIdList(List<String> stationIdList, String begin, String end) {
        QueryWrapper<StationAlarm> query = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(stationIdList)) {
            query.in("station_id", stationIdList);
        }
        query.ge("update_time", begin)
                .le("update_time", end);
        return stationAlarmMapper.selectList(query);
    }
}
